<template>
  <div class="change-password">
    <van-nav-bar
      title="修改密码"
      left-text="返回"
      left-arrow
      @click-left="router.back()"
    />
    
    <van-form @submit="handleSubmit">
      <van-cell-group inset>
        <van-field
          v-model="form.oldPassword"
          type="password"
          name="oldPassword"
          label="原密码"
          placeholder="请输入原密码"
          :rules="[{ required: true, message: '请输入原密码' }]"
        />
        
        <van-field
          v-model="form.newPassword"
          type="password"
          name="newPassword"
          label="新密码"
          placeholder="请输入新密码"
          :rules="[{ required: true, message: '请输入新密码' }]"
        />
        
        <van-field
          v-model="form.confirmPassword"
          type="password"
          name="confirmPassword"
          label="确认密码"
          placeholder="请再次输入新密码"
          :rules="[
            { required: true, message: '请确认新密码' },
            { validator: validateConfirmPassword, message: '两次输入的密码不一致' }
          ]"
        />
      </van-cell-group>
      
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          确认修改
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { changePassword } from '@/api/user'

const router = useRouter()

const form = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const validateConfirmPassword = (value) => {
  return value === form.value.newPassword
}

const handleSubmit = async () => {
  try {
    await changePassword({
      oldPassword: form.value.oldPassword,
      newPassword: form.value.newPassword
    })
    showToast('密码修改成功')
    router.back()
  } catch (error) {
    showToast('密码修改失败')
  }
}
</script>

<style lang="scss" scoped>
.change-password {
  min-height: 100vh;
  background-color: #f7f8fa;
  
  .van-cell-group {
    margin: 12px 0;
  }
}
</style> 